package com.yogee.topseller.activity.login.view.impl;

import android.content.Intent;
import android.os.CountDownTimer;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareConfig;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.yogee.core.base.HttpActivity;
import com.yogee.core.http.loading.CustomProgressDialog;
import com.yogee.core.utils.LogUtils;
import com.yogee.core.utils.ToastUtils;
import com.yogee.topseller.MainActivity;
import com.yogee.topseller.R;
import com.yogee.topseller.activity.MainActivity1;
import com.yogee.topseller.activity.login.model.bean.SMSbean;
import com.yogee.topseller.activity.login.presenter.LoginPresenter;
import com.yogee.topseller.activity.login.view.ILoginView;
import com.yogee.topseller.http.Config;
import com.yogee.topseller.utils.AppUtil;
import com.yogee.topseller.view.ClearEditText;

import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

public class LoginCheckcodeActivity extends HttpActivity implements ILoginView {

    @BindView(R.id.back)
    ImageView back;
    @BindView(R.id.cet_phone)
    ClearEditText cetPhone;
    @BindView(R.id.cet_check_code)
    ClearEditText cetCheckCode;
    @BindView(R.id.get_code)
    TextView getCode;
    @BindView(R.id.login_login)
    TextView loginLogin;
    @BindView(R.id.login_switch)
    TextView loginSwitch;
    @BindView(R.id.sina)
    LinearLayout sina;
    @BindView(R.id.we_chat)
    LinearLayout weChat;
    @BindView(R.id.qq)
    LinearLayout qq;
    @BindView(R.id.bottom)
    LinearLayout bottom;

    LoginPresenter loginPresenter;
    // 1:直接关闭当前Activity
    private String startFlag;

    private UMShareAPI mShareAPI = null;
    // 三方类型 1:微信；2：QQ；3：微博
    private String type = "";

    private String openid, headerUrl, name, sex;

    private int mRadomNumber = 0;

    CustomProgressDialog pd = null;

    private CountDownTimer timer;


    @Override
    protected int getLayoutId() {
        return R.layout.activity_login_checkcode;
    }

    @Override
    protected void initView() {
        loginPresenter = new LoginPresenter(this);
        startFlag = getIntent().getStringExtra("startFlag");
        mShareAPI = UMShareAPI.get(this);
        UMShareConfig config = new UMShareConfig();
        config.isNeedAuthOnGetUserInfo(true);
        UMShareAPI.get(this).setShareConfig(config);
        if (AppUtil.isWeiBoClientAvailable(this)) {
            bottom.setVisibility(View.VISIBLE);
            sina.setVisibility(View.GONE);
        }
        if (AppUtil.isWeixinAvilible(this)) {
            bottom.setVisibility(View.VISIBLE);
            weChat.setVisibility(View.VISIBLE);
        }
        if (AppUtil.isQQClientAvailable(this)) {
            bottom.setVisibility(View.VISIBLE);
            qq.setVisibility(View.GONE);
        }
        mRadomNumber = AppUtil.getRandomNumber(6);
    }

    @OnClick({R.id.back, R.id.get_code, R.id.login_login, R.id.login_switch, R.id.sina, R.id.we_chat, R.id.qq})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:
                if (AppUtil.isFastDoubleClick(500)) {
                    return;
                }
                finish();
                break;
            case R.id.get_code:
                if (AppUtil.isFastDoubleClick(500)) {
                    return;
                }
                if ("重新发送".equals(getCode.getText().toString())) {
                    mRadomNumber = AppUtil.getRandomNumber(6);
                }
                if (TextUtils.isEmpty(cetPhone.getText())) {
                    ToastUtils.showToast(this, "请输入手机号");
                    return;
                } else if (!AppUtil.validatePhone(cetPhone.getText().toString())) {
                    ToastUtils.showToast(this, "请输入正确的手机号");
                    return;
                } else {
                    getCode.setTextColor(getResources().getColor(R.color.gray));
                    getCode.setBackgroundDrawable(getResources().getDrawable(R.drawable.corners5_stroke1gray));
                    getCode.setClickable(false);
                    loginPresenter.sendSMS(LoginCheckcodeActivity.this, cetPhone.getText().toString(), mRadomNumber);
                }
                break;
            case R.id.login_login:
                if (AppUtil.isFastDoubleClick(1000)) {
                    return;
                }
                if (validate()) {
                    TelephonyManager telephonyManager = (TelephonyManager) getSystemService(this.TELEPHONY_SERVICE);//获取CID
                    loginPresenter.login(cetPhone.getText().toString(), "", Config.LOGIN_BY_CHECKCODE, telephonyManager.getDeviceId(),"","");

                }
                break;
            case R.id.login_switch:
                if (AppUtil.isFastDoubleClick(1000)) {
                    return;
                }
                startActivity(new Intent(LoginCheckcodeActivity.this, LoginActivity.class));
                break;
            case R.id.sina:
                if (AppUtil.isFastDoubleClick(1000)) {
                    return;
                }
                resetLoginButton(true);
                type = "3";
                mShareAPI.getPlatformInfo(this, SHARE_MEDIA.SINA, umAuthListener);
                break;
            case R.id.we_chat:
                if (AppUtil.isFastDoubleClick(1000)) {
                    return;
                }
                resetLoginButton(true);
                type = "1";
                mShareAPI.getPlatformInfo(this, SHARE_MEDIA.WEIXIN, umAuthListener);
                break;
            case R.id.qq:
                if (AppUtil.isFastDoubleClick(1000)) {
                    return;
                }
                resetLoginButton(true);
                type = "2";
                mShareAPI.getPlatformInfo(this, SHARE_MEDIA.QQ, umAuthListener);
                break;
        }
    }


    private void resetLoginButton(Boolean flag) {

        if (flag) {
            pd = CustomProgressDialog.createDialog(this);

            sina.setClickable(false);
            weChat.setClickable(false);
            qq.setClickable(false);
        } else {

            if (pd != null)
                pd.dismiss();

            sina.setClickable(true);
            weChat.setClickable(true);
            qq.setClickable(true);
        }
    }

    private UMAuthListener umAuthListener = new UMAuthListener() {
        @Override
        public void onStart(SHARE_MEDIA platform) {
            //授权开始的回调
            LogUtils.e("test", "onStart");
        }

        @Override
        public void onComplete(SHARE_MEDIA platform, int action, Map<String, String> data) {

            LogUtils.e("test", "onComplete");
            openid = data.get("uid");
            headerUrl = data.get("iconurl");
            name = data.get("name");
            sex = "男".equals(data.get("gender")) ? "1" : "0";

            resetLoginButton(false);

            TelephonyManager telephonyManager = (TelephonyManager) getSystemService(LoginCheckcodeActivity.this.TELEPHONY_SERVICE);//获取CID
            loginPresenter.otherLogin(openid, name, headerUrl,telephonyManager.getDeviceId());

        }

        @Override
        public void onError(SHARE_MEDIA platform, int action, Throwable t) {
            LogUtils.e("test", "onError");
            resetLoginButton(false);
        }

        @Override
        public void onCancel(SHARE_MEDIA platform, int action) {
            LogUtils.e("test", "onCancel");
            resetLoginButton(false);
        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        LogUtils.e("test", "onActivityResult");
        mShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public Boolean validate() {
        if (cetPhone.getText().length() == 0) {
            ToastUtils.showToast(this, "请填写电话");
            return false;
        } else if (cetPhone.getText().length() != 11) {
            ToastUtils.showToast(this, "请填写11位手机号");
            return false;
        } else if (cetCheckCode.getText().toString().length() == 0) {
            ToastUtils.showToast(this, "请填写验证码");
            return false;
        } else if (!cetCheckCode.getText().toString().equals(String.valueOf(mRadomNumber))) {
            ToastUtils.showToast(this, "验证码输入错误");
            return false;
        }
        {
            return true;
        }
    }

    @Override
    public void loginSuccess() {
        if (TextUtils.isEmpty(startFlag)) {
            startActivity(new Intent(this, MainActivity1.class));
        }

        finish();
    }

    @Override
    public void checkCode(SMSbean smSbean) {
        if (Integer.parseInt(smSbean.getError_code()) == 0) {
            countDownTimer();
            ToastUtils.showToast(this, "验证码已经发送");
        } else {
            getCode.setClickable(true);
            ToastUtils.showToast(this, smSbean.getError_code() + ":" + smSbean.getReason());
        }
    }

    public void countDownTimer() {

        timer = new CountDownTimer(60000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                getCode.setText("重新发送" + "(" + millisUntilFinished / 1000 + "s)");
                getCode.setTextColor(getResources().getColor(R.color.gray));
                getCode.setBackgroundDrawable(getResources().getDrawable(R.drawable.corners5_stroke1gray));
                getCode.setClickable(false);
            }

            @Override
            public void onFinish() {
                getCode.setText("重新发送");
                getCode.setTextColor(getResources().getColor(R.color.theme_color));
                getCode.setBackgroundDrawable(getResources().getDrawable(R.drawable.corners5_stroke1_theme));
                getCode.setClickable(true);
            }
        };
        timer.start();
    }
}
